package com.sale.plugins;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.match.common.Constant;
import com.apache.tools.DataMap;
import com.apache.tools.NumberUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 委托买入判断是否超过持仓总订货量（持仓上限）设置
 */
public class SaleMaxNumGoodsPluginImpl implements CustomMethodPlugin {

    private Logger log = Logger.getLogger(getClass());

    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
        String orderFlag = String.valueOf(param.get("trsOrder.orderFlag"));
        String proId = String.valueOf(param.get("trsOrder.proId"));
        String proNo = String.valueOf(param.get("trsOrder.proNo"));
        String proName = String.valueOf(param.get("trsOrder.proName"));
        String userId = String.valueOf(param.get("trsOrder.userId"));
        String userEname = String.valueOf(param.get("trsOrder.userEname"));
        String orderNum = String.valueOf(param.get("trsOrder.orderNum"));
        String totalNum = String
                .valueOf(param.get("totalNum"));//应该来自SaleBuyForGoodsPluginImpl中填充的参数

        if (Validator.isNotNull(orderFlag) && "buy".equals(orderFlag)) {
            log.info(userEname + "-委托买入判断是否超过产品持仓总订货量（持仓上限）设置....");

            List<DataMap> rulesListMap = getMaxGoodsRules(param, proId);
            if (rulesListMap == null || rulesListMap.size() < 1) {
                log.info("未找到产品持仓总订货量（持仓上限）设置参数");
                return null;
            }
            String rulesMaxParam = "0";
            for (DataMap dm : rulesListMap) {
                String paramVal = String.valueOf(dm.get("paramNo"));
                String rulesNo = String.valueOf(dm.get("rulesNo"));
                if ("order19".equals(rulesNo)) {
                    rulesMaxParam = paramVal;
                }
            }
            if (!"0".equals(rulesMaxParam)) {
                long orderUseAmount = getOrderUseAmount(userId, proId);
                log.info("1)获取所有买入委托单(未成交+未撤单)被占用的数量总和=>" + orderUseAmount);

                long totalNumLong = Long.valueOf(totalNum);
                long rulesVal = Long.valueOf(rulesMaxParam);
                long orderNumLong = Long.valueOf(orderNum);
                long totalAllCount = (totalNumLong + orderUseAmount + orderNumLong);
                log.info("2)判断：持仓[" + proNo + "]的历史总量[" + totalNum + "]+占用的数量[" + orderUseAmount
                        + "]+本次买入量[" + orderNum + "]=[" + totalAllCount + "],是否超过获取规则设置参数["
                        + rulesMaxParam + "]");
                if (totalAllCount > rulesVal) {
                    throw new BusinessException(
                            "累计您委托买入量已超过【" + proNo + "-" + proName + "】订货量上限设置[" + rulesVal + "]");
                }
            } else {
                log.info(userEname + "-订货上限验证结果未设置或者设置为0：故不限制");
            }
        }

        return null;
    }

    /**
     * 查询商品设置的:交易商订货量（持仓上限）设置值
     *
     * @param param
     * @param proId
     * @return
     */
    @SuppressWarnings("rawtypes")
    public List<DataMap> getMaxGoodsRules(Map<String, Object> param, String proId) {
//        ProxyManager netProxyManager = (ProxyManager) SpringContextLoader
//                .getBean("netProxyManager");
//        ParamsVo params = new ParamsVo();
//        params.setParams("doCode", "dymicSql");
//        params.setParams("sqlKeyId", "ByDymicSql");
//        params.setParams("resultType", "objInfo");
//        params.setKey("publicForSql");
//
//        //封装参数
//        params.setParams("modelTypes", "s_trsRulesPro");
//
//        params.setParams("trsRulesPro.w_showFlag", "T");
//        params.setParams("trsRulesPro.w_rulesType", "guadan");
//        params.setParams("trsRulesPro.w_constantType", "order_status");
//        params.setParams("trsRulesPro.w_dataType", "datetext");
//        params.setParams("trsRulesPro.w_prodId", proId);
//        params.setParams("trsRulesPro.w_rulesNo", "order19");
//        params.setParams("orderBy", "trsRulesPro.rules_no nulls last");

//        ResultEntity dymicSqlParamResult = (ResultEntity) netProxyManager.doInvoke(params);
//        List<DataMap> list = (List) dymicSqlParamResult.getEntity();

        Map<String, Object> whereMap = new HashMap<String,Object>();
        //封装参数
        whereMap.put("trsRulesPro.w_showFlag", "T");
        whereMap.put("trsRulesPro.w_rulesType", "guadan");
        whereMap.put("trsRulesPro.w_constantType", "order_status");
        whereMap.put("trsRulesPro.w_dataType", "datetext");
        whereMap.put("trsRulesPro.w_prodId", proId);
        whereMap.put("trsRulesPro.wl_rulesNo", "order19");
        whereMap.put("orderBy", "trsRulesPro.rules_no asc");

        ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("list","s_trsRulesPro",whereMap);
        if(resultEntity1==null || resultEntity1.getEntity()==null){
            throw new BusinessException("查询规则失败！");
        }
        List<DataMap> list = (List<DataMap>)resultEntity1.getEntity();
        if(list==null || list.size()==0){
            throw new BusinessException("查询规则失败！");
        }
        return list;
    }

    /**
     * 获取所有买入委托单未成交被占用的数量总和
     *
     * @param userId
     * @return
     */
    @SuppressWarnings("rawtypes")
    public long getOrderUseAmount(String userId, String proId) {
//        ProxyManager netProxyManager = (ProxyManager) SpringContextLoader
//                .getBean("netProxyManager");
//        ParamsVo params = new ParamsVo();
        String dataType = Constant.getDatabaseType("sale");
        String returnKeyName = "useamount";
//        params.setParams("sqlKeyId", "ByObjInfo");
//        params.setKey("publicForSql");
        StringBuffer dyncSql = new StringBuffer("select ");
        if ("oracle".equalsIgnoreCase(dataType)) {
            dyncSql.append(" nvl(sum(o.order_num-nvl(o.deal_num,0)),0) ");
        }
        if ("mysql".equalsIgnoreCase(dataType)) {
            dyncSql.append("  cast(IFNULL(sum(o.order_num - IFNULL(o.deal_num, 0)),0)  as signed) ");
        }
        dyncSql.append("  as " + returnKeyName + " from trs_order o ");
        dyncSql.append(" where o.is_deal in('F','T01') and o.del_status='F' and o.order_flag='buy'  ");
        dyncSql.append(" and o.pro_id='" + proId + "'");
        dyncSql.append(" and o.user_id='" + userId + "'");

//        params.setParams("dyncSql", dyncSql.toString());
//        ResultEntity dymicSqlParamResult = (ResultEntity) netProxyManager.doInvoke(params);
//        List<DataMap> list = (List) dymicSqlParamResult.getEntity();

        List<DataMap> list = (List)IusPluginUtil.getInstance().select(dyncSql.toString(),0,0);
        if (list != null && list.size() > 0) {
            DataMap numMap = list.get(0);
            if (numMap.containsKey(returnKeyName)) {
                long totalNum = Long.valueOf(String.valueOf(numMap.get(returnKeyName)));
                return totalNum;
            }
        }
        return 0;
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {

        // TODO Auto-generated method stub
        return null;
    }

    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

}
